package com.zhuiyun.project.api.messagelist.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zhuiyun.project.api.appuser.service.AppUserService;
import com.zhuiyun.project.api.friend.service.FriendService;
import com.zhuiyun.project.api.group.entity.Group;
import com.zhuiyun.project.api.group.service.GroupService;
import com.zhuiyun.project.api.groupmessage.entity.GroupMessage;
import com.zhuiyun.project.api.groupmessage.model.GroupMessageModel;
import com.zhuiyun.project.api.groupmessage.service.GroupMessageService;
import com.zhuiyun.project.api.joingroup.entity.JoinGroup;
import com.zhuiyun.project.api.message.config.MessageType;
import com.zhuiyun.project.api.message.entity.Message;
import com.zhuiyun.project.api.message.mapper.MessageMapper;
import com.zhuiyun.project.api.message.service.MessageService;
import com.zhuiyun.project.api.messagelist.entity.MessageList;
import com.zhuiyun.project.api.messagelist.mapper.MessageListMapper;
import com.zhuiyun.project.api.messagelist.model.MessageListModel;
import com.zhuiyun.project.api.messagelist.service.MessageListService;
import com.zhuiyun.project.api.personmessage.entity.PersonMessage;
import com.zhuiyun.project.api.personmessage.mapper.PersonMessageMapper;
import com.zhuiyun.project.api.personmessage.service.PersonMessageService;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName MessageListServiceImpl
 * @Description TODO
 * @Author kdj
 * @Date 2023/6/28 14:36
 **/
@Service
public class MessageListServiceImpl implements MessageListService {
    @Autowired
    private MessageListMapper messageListMapper;
    @Autowired
    private MessageService messageService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private PersonMessageService personMessageService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private GroupMessageService groupMessageService;

    /**
     * @param messageId
     * @Author kdj
     * @Description 更新 消息列表
     * @Date 2023/6/28 15:29
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer updateChatList(int messageId) {
        //根据messageId查询出相对应的详细的message信息
        Map message = messageService.getMsgSm(messageId);
        //判断是否为空
        if (message == null) {
            return 0;
        }
        //获取message的类型
        int type = Integer.parseInt(message.get("type").toString());
        //获取message的数据
        Object data = message.get("data");
        //不为空 判断message的类型
        switch (type) {
            case MessageType.PerMsgType: //单聊
                //取personMessage的数据
                PersonMessage personMessage = (PersonMessage) data;
                //查找之前是否有相关的聊天列表
                MessageList messageList = this.getPerMsgListByTwoId(personMessage.getFromId(), personMessage.getToId(), MessageType.PerMsgType);
                //查找之前是否有相关的聊天列表
                MessageList messageList2 = this.getPerMsgListByTwoId(personMessage.getToId(), personMessage.getFromId(), MessageType.PerMsgType);
                //判断最后一体消息是否是撤回
                if (personMessage.getIsWithdraw() == 1) {
                    // 撤回消息
                    updateWithdrawMessage(messageList, messageList2);
                } else {
                    //判断最后一条消息的类型
                    String content = MessageType.getLastContent(personMessage.getMsgType(), personMessage.getContent());
                    //发送最后一条的时间
                    Date lastTime = personMessage.getCreateTime();
                    //根据发送者的id获取他的userName
                    //获取我给好友的备注
                    //如果我没给好友备注
                    //则获取我的的用户名
                    String userName = friendService.getUserRemarkName(personMessage.getToId(), personMessage.getFromId());
                    if (!ObjectUtils.isNotEmpty(userName)) {
                        userName = appUserService.getUserByUserId(personMessage.getFromId()).getUserName();
                    }
                    //获取好友给本人的备注
                    String userName2 = friendService.getFriendRemarkName(personMessage.getToId(), personMessage.getFromId());
                    //如果好友没给我备注
                    //则回去他的用户名
                    if (!ObjectUtils.isNotEmpty(userName2)) {
                        userName2 = appUserService.getUserByUserId(personMessage.getToId()).getUserName();
                    }
                    //获取好友头像
                    int avatarId2 = appUserService.getAvatarId(personMessage.getFromId());
                    //获取本人头像
                    int avatarId1 = appUserService.getAvatarId(personMessage.getToId());
                    Integer fromId = personMessage.getFromId();
                    Integer toId = personMessage.getToId();
                    //主动发送消息的用户不需要设置未读数
                    //messageList2不需要增加未读数
                    updateMsgList(messageList, messageId, content, lastTime, userName, avatarId2, fromId, toId, true);
                    updateMsgList(messageList2, messageId, content, lastTime, userName2, avatarId1, toId, fromId, false);
                }
                break;
            case MessageType.GroupMsgType:
                //取personMessage的数据
                GroupMessage groupMessage = (GroupMessage) data;
                //判断最后一条消息的类型
                String content = MessageType.getLastContent(groupMessage.getMsgType(), groupMessage.getContent());
                groupMessage.setContent(content);
                //批量修改
                //判断没有推出群的用户然后修改修改时间 未读数加1
                messageListMapper.upGroupMsgLists(groupMessage);
                break;
            // TODO  其他类型没写
        }


        return 1;
    }

    /**
     * @param fromId
     * @param toId
     * @Author kdj
     * @Description 根据fromId和toId查询到messageList
     * @Date 2023/6/28 19:16
     * @Return com.zhuiyun.project.api.messagelist.entity.MessageList
     */
    @Override
    public MessageList getPerMsgListByTwoId(int fromId, int toId, int type) {
        Example example = new Example(MessageList.class);
        example.createCriteria().andEqualTo("toId", toId).andEqualTo("fromId", fromId).andEqualTo("type", type).andEqualTo("delFlag",0);
        MessageList messageList = messageListMapper.selectOneByExample(example);
        return messageList;
    }

    /**
     * @param fromId
     * @param toId
     * @param type   类型
     * @param num    未读信息数量
     * @Author kdj
     * @Description 根据fromId和toId修改未读信息数量
     * @Date 2023/6/28 19:20
     * @Return void
     */
    @Override
    public void upMsgListUmReadZero(int fromId, int toId, int type, int num, boolean isAdd) {
        //查询相关的messageList
        MessageList messageList = this.getPerMsgListByTwoId(fromId, toId, type);
        Integer unReadNum = messageList.getUnReadNum();
        int newNum;
        //判断未读信息的值
        if (num == 0) {
            newNum = 0;
        } else if (isAdd == true) {
            newNum = num + unReadNum;
        } else {
            newNum = unReadNum - num;
        }
        //清空未读信息
        messageList.setUnReadNum(newNum);
        //修改时间
        messageList.setUpdateTime(new Date());
        messageListMapper.updateByPrimaryKeySelective(messageList);
    }
    /**
     * @param userId
     * @Author kdj
     * @Description 获取信息列表
     * @Date 2023/6/28 20:23
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getMsgList(int userId) {
       List<MessageList>  messageLists= messageListMapper.getMsgList(userId);
        return CommonResult.ok(messageLists);
    }
    /**
     * @param joinGroup
     * @Author kdj
     * @Description 创建群聊聊天列表
     * @Date 2023/7/28 17:04
     * @Return com.zhuiyun.project.api.messagelist.entity.MessageList
     */
    @Override
    public MessageList createGroupMsgList(JoinGroup joinGroup) {
        //根据groupId获取Group
        Group group = groupService.getGroupByGroupId(joinGroup.getGroupId());
        //创建messageList
        MessageList messageList = new MessageList();
        //群名称
        messageList.setListName(group.getGroupName());
        //群头像
        messageList.setFromAvatarId(group.getGroupImgId());
        //setFromId是群聊的 id
        //toId是当前登录者的id
        messageList.setFromId(joinGroup.getGroupId());
        messageList.setToId(joinGroup.getUserId());
        //未读数为0
        messageList.setUnReadNum(0);
        //创建时间
        messageList.setCreateTime(new Date());
        messageList.setUpdateTime(new Date());
        //删除标志为0
        messageList.setDelFlag(0);
        //群聊类型
        messageList.setType(MessageType.GroupMsgType);
        GroupMessageModel groupChatLast = groupMessageService.getGroupChatLast(joinGroup.getGroupId());
        if(groupChatLast!=null) {
            //最后一条消息
            messageList.setLastMessageTime(groupChatLast.getCreateTime());
            messageList.setLastMessageId(groupChatLast.getMessageId());
            String lastContent = MessageType.getLastContent(groupChatLast.getMsgType(), groupChatLast.getContent());
            messageList.setLastMessageContent(lastContent);
        }
        int i = messageListMapper.insertSelective(messageList);
        if (i > 0) {
            return messageList;
        }
        return null;

    }

    /**
     * @param groupMessage
     * @Author kdj
     * @Description 撤回群聊消息修改msgList
     * @Date 2023/7/31 16:39
     * @Return void
     */
    @Override
    @Transactional
    public void upMsgGroupListByRecall(GroupMessage groupMessage) {
        //判断是主动撤回还是被动
        Integer withdrawUserId = groupMessage.getWithdrawUserId();
        if (withdrawUserId == 0) {
            //主动
            //修改当前用户的msg为 我撤回
            //其他用户是xxx用户
            //根据groupMsg获取发送者的userName
            String fromName = groupMessageService.getFromName(groupMessage);
            String lastMessageContent = fromName + "撤回了一条消息";
            String lastMessageContentMe = "你撤回了一条消息";
            //判断发送者是不是sys
            if (groupMessage.getUserType() == MessageType.socketSysNum) {
                //其他的都该
                //群id 撤回人 id type
                messageListMapper.upMsgGroupListByRecallOther(groupMessage.getToId(), groupMessage.getFromId(), 0, lastMessageContent);
            } else {
                //群id 撤回人 id type
                messageListMapper.upMsgGroupListByRecallOther(groupMessage.getToId(), groupMessage.getFromId(), groupMessage.getUserType(), lastMessageContent);
                messageListMapper.upMsgGroupListByRecallMe(groupMessage.getToId(), groupMessage.getFromId(), groupMessage.getUserType(), lastMessageContentMe);
            }
        } else {
            String lastMessageContent = "管理员撤回了一条消息";
            messageListMapper.upMsgGroupListByRecallOther(groupMessage.getToId(), groupMessage.getFromId(), 0, lastMessageContent);

        }


    }

    /**
     * @param fromId
     * @param toId
     * @param MsgType
     * @param msgId
     * @Author kdj
     * @Description 修改消息列表的last等消息
     * @Date 2023/7/31 11:12
     * @Return void
     */
    public void upMsgListLastInfo(Integer fromId, Integer toId, int MsgType, int msgId, int userId) {
        Integer lastMessageId = null;
        String lastMessageContent = null;
        Date lastMessageTime = null;
        //查询相关的messageList
        MessageList messageList = this.getPerMsgListByTwoId(fromId, toId, MsgType);
        //根据userId获取一下用户名字
        //判断类型
        if (MsgType == MessageType.PerMsgType) {
            //单聊的话查一下单聊的最后消息
            PersonMessage msgLastInfo = personMessageService.getMsgLastInfo(fromId, toId, userId);
            //判断是否为空
            if (msgLastInfo != null) {
                //判断是否被撤回了
                if (msgLastInfo.getIsWithdraw() == 1) {
                    //判断发送者是不是自己
                    if (msgLastInfo.getFromId() == userId) {
                        //如果是的话
                        lastMessageContent = "你撤回了一条消息";
                    } else {
                        lastMessageContent = "对方撤回了一条消息";
                    }
                } else {
                    lastMessageContent = MessageType.getLastContent(msgLastInfo.getMsgType(), msgLastInfo.getContent());
                }
                lastMessageId = msgLastInfo.getMessageId();
                lastMessageTime = msgLastInfo.getCreateTime();
            }
        } else if (MsgType == MessageType.GroupMsgType) {
            //群聊的话查一下群聊聊的最后消息
            GroupMessage msgLastInfo = groupMessageService.getMsgLastInfo(fromId, toId, userId);

            //判断是否为空
            if (msgLastInfo != null) {  //查看该消息是谁发送的
                if(msgLastInfo.getMsgType()==MessageType.socketSysNum){
                    return;
                }
                //判断是否被撤回了
                if (msgLastInfo.getIsWithdraw() == 1) {
                    //判断发送者是不是自己
                    //判断是不是被动撤回的
                    if (msgLastInfo.getWithdrawUserId() == 1) {
                        //如果是的话
                        lastMessageContent = "管理员撤回了一条消息";
                    } else {
                        if (msgLastInfo.getFromId() == userId) {
                            //如果是的话
                            lastMessageContent = "你撤回了一条消息";
                        } else {
                            //根据groupMsg获取发送者的userName
                            String fromName = groupMessageService.getFromName(msgLastInfo);
                            lastMessageContent = fromName + "撤回了一条消息";
                        }
                    }
                } else {
                    lastMessageContent = MessageType.getLastContent(msgLastInfo.getMsgType(), msgLastInfo.getContent());
                }
                lastMessageId = msgLastInfo.getMessageId();
                lastMessageTime = msgLastInfo.getCreateTime();
            }
        }
        //修改
        messageListMapper.upListLast(lastMessageId, lastMessageContent, lastMessageTime, messageList.getId());
    }

    /**
     * @param messageList
     * @param messageList2
     * @Author kdj
     * @Description 修改撤回消息的字段
     * @Date 2023/7/19 21:19
     * @Return void
     */
    private void updateWithdrawMessage(MessageList messageList, MessageList messageList2) {
        if (messageList != null && messageList2 != null) {
            messageList.setLastMessageContent("对方撤回了一条消息");
            messageList2.setLastMessageContent("你撤回了一条消息");
            messageListMapper.updateByPrimaryKeySelective(messageList);
            messageListMapper.updateByPrimaryKeySelective(messageList2);
        }
    }

    /**
     * @param messageList
     * @param messageId
     * @param content
     * @param lastTime
     * @param userName
     * @param avatarId2
     * @param fromId
     * @param toId
     * @param isFrom
     * @Author kdj
     * @Description 修改 messageList对象
     * @Date 2023/7/20 9:10
     * @Return void
     */
    void updateMsgList(MessageList messageList, int messageId, String content, Date lastTime, String userName,
                       int avatarId2, int fromId, int toId, boolean isFrom) {
        //未读数的变量
        int num = 0;
        //判断是否主动接收消息的
        if (isFrom) {
            //如果 当前是的话 未读数加1
            num = 1;
        }
        //判断是否为空
        if (ObjectUtil.isEmpty(messageList)) {
            messageList = new MessageList();
        }
        messageList.setLastMessageId(messageId);
        messageList.setLastMessageContent(content);
        messageList.setLastMessageTime(lastTime);
        messageList.setListName(userName);
        messageList.setFromAvatarId(avatarId2);
        messageList.setDelFlag(0);
        messageList.setUpdateTime(new Date());
        //判断是否为空
        if (ObjectUtil.isNotEmpty(messageList.getFromId())) {
            //修改
            //纬度数量＋1
            messageList.setUnReadNum(messageList.getUnReadNum() + num);
            messageListMapper.updateByPrimaryKeySelective(messageList);
        } else {
            //添加
            messageList.setUnReadNum(num);
            messageList.setFromId(fromId);
            messageList.setToId(toId);
            messageList.setType(MessageType.PerMsgType);
            messageList.setUpdateTime(new Date());
            messageListMapper.insert(messageList);
        }
    }
}
